package com.shunda.pay.utils;

import com.shunda.common.exception.ServiceException;
import com.shunda.pay.config.WxPayConfig;
import com.shunda.pay.dto.WxChatReceiversAddDto;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.profitsharing.model.DeleteReceiverRequest;
import com.wechat.pay.java.service.profitsharing.model.DeleteReceiverResponse;
import com.wechat.pay.java.service.profitsharing.model.ReceiverType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 删除分账接收方工具类
 */
public class WxPayReceiversDelUtil {

    private static final Logger log = LoggerFactory.getLogger(WxPayReceiversDelUtil.class);

    /**
     * 封装微信分账参数
     *
     * @param dto 分账请求参数
     * @return 封装后的map微信分账对象
     */
    private static DeleteReceiverRequest getReceiversDelParams(WxPayConfig wxPayConfig, WxChatReceiversAddDto dto) {
        DeleteReceiverRequest request = new DeleteReceiverRequest();
        request.setAppid(wxPayConfig.getAppId());
        request.setType(ReceiverType.valueOf(dto.getType()));
        request.setAccount(dto.getAccount());
        return request;
    }

    /**
     * 删除微信分账参数
     *
     * @param wxPayConfig 微信配置信息
     * @param param       微信支付申请退款请求参数
     * @return 成功：true，失败：false
     */
    public static boolean receiversDel(WxPayConfig wxPayConfig, WxChatReceiversAddDto param,
                                       RSAAutoCertificateConfig rsaAutoCertificateConfig) {
        ProfitsharingService service =
                new ProfitsharingService.Builder()
                        .config(rsaAutoCertificateConfig)
                        .build();
        DeleteReceiverResponse response = null;
        try {
            DeleteReceiverRequest request = getReceiversDelParams(wxPayConfig, param);
            response = service.deleteReceiver(request);
        } catch (HttpException e) { // 发送HTTP请求失败
            log.error("微信添加分账账户发送HTTP请求失败，错误信息：{}", e.getHttpRequest());
        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300，例如500
            log.error("微信添加分账账户服务状态错误，错误信息：{}", e.getMessage());
        } catch (MalformedMessageException e) { // 服务返回成功，返回体类型不合法，或者解析返回体失败
            log.error("服务返回成功，返回体类型不合法，或者解析返回体失败，错误信息：{}", e.getMessage());
        }
        return response != null;
    }
}
